package com.wechar_rpa.service;

import com.wechar_rpa.model.ChatMessage;
import com.wechar_rpa.model.User;
import com.wechar_rpa.repository.ChatMessageRepository;
import com.wechar_rpa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ChatMessageService {

    @Autowired
    private ChatMessageRepository chatMessageRepository;

    @Autowired
    private UserRepository userRepository;

    public ChatMessage saveMessage(ChatMessage message) {
        if (message.getTimestamp() == null) {
            message.setTimestamp(new Date());
        }

        // 确保群聊和文件字段非空时才保存
        if (message.isGroupMessage() != null && message.isGroupMessage()) {
            chatRecordRepository.save(message);  // MongoDB 存储群聊消息
        } else if (message.isFileMessage() != null && message.isFileMessage()) {
            chatRecordRepository.save(message);  // MongoDB 存储文件消息
        } else {
            return chatMessageRepository.save(message);  // MySQL 存储私聊消息
        }
        return message;
    }

    public List<ChatMessage> getRecentMessagesForUser(String userId) {
        return chatMessageRepository.findByUserIdAndIsWhitelistedTrue(userId);
    }

    public List<ChatMessage> getGroupMessages() {
        return chatMessageRepository.findByIsGroupMessageTrue();
    }

    public List<ChatMessage> getFileMessages() {
        return chatMessageRepository.findByIsFileMessageTrue();
    }
}